 

import Foundation


extension Date {
    
    private static let sharedDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone.current
        return formatter
    }()
    
    
    func toString(withFormat format: String) -> String {
        Date.sharedDateFormatter.dateFormat = format
        return Date.sharedDateFormatter.string(from: self)
    }
    
    static func dateWithString(date: String, format: String) -> Date? {
        Date.sharedDateFormatter.dateFormat = format
        return Date.sharedDateFormatter.date(from: date)
    }
    
    /// 根据时间戳（单位可以是秒或毫秒）创建 Date
    static func from(timestamp: TimeInterval) -> Date {
        // 如果时间戳大于 10^10，则认为是毫秒（大概是 2001 年之后的时间）
        let adjustedTimestamp = timestamp > 1_000_000_000_0 ? timestamp / 1000 : timestamp
        return Date(timeIntervalSince1970: adjustedTimestamp)
    }
    
}
